{-# LANGUAGE ForeignFunctionInterface #-}
import qualified Data.ByteString.Lazy as BL
import Data.List (concatMap,groupBy,filter)
import Graphics.UI.SDL
import Obscure
import System.Environment (getArgs)
import Foreign (Ptr, withForeignPtr)
import Foreign.C.String

width :: Int
width = 512

maxHeight :: Int
maxHeight = 341

--extern "C" void writeXPM(SDL_Surface *surf, const char *fname) {
foreign import ccall unsafe "writeXPM" writeXPM :: Ptr SurfaceStruct -> CString -> IO ()


getResolution :: Int -> IO (Int, Surface)
getResolution x = gr 1
    where gr f | x `div` f < maxHeight * width = let size' = x `div` f
                                                     h = size' `div` width
                                                 in do d <- setVideoMode width (h+1) 32 []
                                                       return (f, d)
               | otherwise = gr $ f + 1

display :: String -> IO ()
display fn = do
  dat <- BL.readFile fn
  (f, s) <- getResolution $ fromIntegral $ BL.length dat
  setCaption fn fn
  let i = interestingRollingDifference dat
  let i1 = Data.List.filter (\(_,x,_) -> x > 3) i
  let i2 = map (\(p, l, v) -> (p `div` f, l `div` f, v)) i1
  let i3 = Data.List.concatMap (\(p, l, v) -> zip [p..p + l] $ repeat v) i2
  mapM_ (\(p, v) -> pixl s (p `mod` width) (p `div` width) v) i3
  Graphics.UI.SDL.flip s
  withForeignPtr s $ withCString (fn ++ ".xpm") . writeXPM
  delay 2200
  
main :: IO ()
main = do
  fn <- getArgs
  withInit [InitVideo] $ mapM_ display fn
